// -----------------------------------------------------------------------
//  <copyright file="CreateUserCommand.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/10 16:07:27</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Identity.Domain.Entities;
using DaprPlus.Identity.Domain.IntegrationEvents;

using DaprPlus.Identity.Application.Identity.Users.Queries;

using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;

namespace DaprPlus.Identity.Application.Identity.Users.Commands;

[AuthConfig(typeof(User), ResourceAccessType.RoleLimit, "Create")]
public class CreateUserCommand : IRequest<ApiResult>, ICommand
{
    public required UserInDto[] Dtos { get; set; }
}

public class CreateUserCommandHandler(IServiceProvider provider)
    : IRequestHandler<CreateUserCommand, ApiResult>
{
    public async Task<ApiResult> Handle(CreateUserCommand request, CancellationToken cancellationToken)
    {
        var userManager = provider.GetRequiredService<UserManager<User>>();
        var repository = provider.GetRepository<User>();
        var createdUsers = new List<UserRecord>();

        foreach (var dto in request.Dtos)
        {
            var entity = dto.MapTo<User>();
            entity.SetId();

            var result = string.IsNullOrEmpty(dto.Password)
                ? await userManager.CreateAsync(entity)
                : await userManager.CreateAsync(entity, dto.Password);
            if (!result.Succeeded)
            {
                return new ApiResult(ApiResultType.Error, result.Errors.First().Description);
            }

            var spec = new UserByIdSpec<User>(entity.Id);
            entity = await repository.GetAsync(spec, cancellationToken);
            if (entity != null)
            {
                createdUsers.Add(new UserRecord(entity.Id, entity.UserName, entity.NickName ?? entity.UserName, entity.IsLocked));
            }
        }

        var @event = new UserCreatedIntegrationEvent([.. createdUsers]);
        var uow = provider.GetUnitOfWork();
        uow.AddIntegrationEvent(@event);

        var userNames = createdUsers.ExpandAndToString(m => m.NickName);
        return new ApiResult(ApiResultType.Success, $"用户 {userNames} 创建成功");
    }
}

